<script setup>
import { ref, computed } from 'vue'
import { useCanvasStore } from '@/stores/canvas'
import { message } from 'ant-design-vue'

const canvasStore = useCanvasStore()
const fileInputRef = ref()

// 计算选中状态
const selectedComponents = computed(() => canvasStore.selectedComponents)
const canGroup = computed(() => selectedComponents.value.length >= 2)
const canUngroup = computed(() =>
  selectedComponents.value.length === 1 &&
  selectedComponents.value[0]?.type === 'group'
)

// 页面管理相关状态
const showPageModal = ref(false)
const showRenameModal = ref(false)
const renamingPageId = ref('')
const newPageName = ref('')
const pages = computed(() => canvasStore.pageState.pages)
const currentPageId = computed(() => canvasStore.pageState.currentPageId)
const currentPage = computed(() => canvasStore.currentPage)

// 导出配置（导出所有页面）
const exportConfig = () => {
  try {
    const config = canvasStore.exportConfig()
    const blob = new Blob([JSON.stringify(config, null, 2)], { type: 'application/json' })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    const timestamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, -5)
    a.download = `indupanel-${timestamp}.json`
    a.click()
    URL.revokeObjectURL(url)
    message.success(`成功导出 ${config.pages.length} 个页面`)
  } catch (error) {
    message.error('导出失败: ' + error.message)
  }
}

// 导入配置
const importConfig = () => {
  fileInputRef.value?.click()
}

const handleFileChange = (event) => {
  const file = event.target.files?.[0]
  if (!file) return

  const reader = new FileReader()
  reader.onload = (e) => {
    try {
      const config = JSON.parse(e.target?.result)
      canvasStore.importConfig(config)
      message.success('配置导入成功')
    } catch (error) {
      message.error('导入失败: 文件格式不正确')
    }
  }
  reader.readAsText(file)

  // 清空input值，允许重复选择同一文件
  event.target.value = ''
}

// 清空画布
const clearCanvas = () => {
  canvasStore.clearCanvas()
  message.success('画布已清空')
}

// 组合组件
const groupSelectedComponents = () => {
  const selectedIds = canvasStore.canvasState.selectedComponentIds
  if (selectedIds.length >= 2) {
    canvasStore.groupComponents(selectedIds)
    message.success(`成功合并${selectedIds.length}个组件`)
  }
}

// 打散组合
const ungroupSelectedComponent = () => {
  const selected = selectedComponents.value[0]
  if (selected && selected.type === 'group') {
    canvasStore.ungroupComponent(selected.id)
    message.success('成功打散组合')
  }
}

// 页面管理功能
const handleCreatePage = () => {
  const pageName = `页面${pages.value.length + 1}`
  canvasStore.createPage(pageName)
  message.success(`创建页面：${pageName}`)
}

const handleSwitchPage = (pageId) => {
  canvasStore.switchPage(pageId)
}

const handleDeletePage = (pageId) => {
  if (pages.value.length === 1) {
    message.warning('至少保留一个页面')
    return
  }
  canvasStore.deletePage(pageId)
  message.success('页面已删除')
}

const openRenameModal = (pageId, currentName) => {
  renamingPageId.value = pageId
  newPageName.value = currentName
  showRenameModal.value = true
}

const handleRenamePage = () => {
  if (!newPageName.value.trim()) {
    message.warning('页面名称不能为空')
    return
  }
  canvasStore.renamePage(renamingPageId.value, newPageName.value)
  message.success('页面重命名成功')
  showRenameModal.value = false
}

const handleDuplicatePage = (pageId) => {
  const newPage = canvasStore.duplicatePage(pageId)
  if (newPage) {
    message.success(`已复制页面：${newPage.name}`)
  }
}
</script>

<template>
  <div class="toolbar h-12 bg-white border-b border-gray-200 flex items-center justify-between px-4">
    <div class="flex items-center space-x-4">
      <h1 class="text-lg font-semibold text-gray-800">InduPanel</h1>
      
      <!-- 页面管理 -->
      <a-divider type="vertical" />
      
      <!-- 页面标签 -->
      <div class="flex items-center space-x-2">
        <a-dropdown v-for="page in pages" :key="page.id">
          <a-tag 
            :color="page.id === currentPageId ? 'blue' : 'default'" 
            class="cursor-pointer px-3 py-1"
            @click="handleSwitchPage(page.id)"
          >
            {{ page.name }}
          </a-tag>
          <template #overlay>
            <a-menu>
              <a-menu-item @click="openRenameModal(page.id, page.name)">
                ✏️ 重命名
              </a-menu-item>
              <a-menu-item @click="handleDuplicatePage(page.id)">
                📋 复制
              </a-menu-item>
              <a-menu-item danger @click="handleDeletePage(page.id)" :disabled="pages.length === 1">
                🗑️ 删除
              </a-menu-item>
            </a-menu>
          </template>
        </a-dropdown>
        
        <!-- 新建页面按钮 -->
        <a-button size="small" type="dashed" @click="handleCreatePage">
          + 新建页面
        </a-button>
      </div>
    </div>

    <div class="flex items-center space-x-2">
      <!-- 撤销重做 -->
      <a-button size="small" :disabled="!canvasStore.canUndo" @click="canvasStore.undo" title="撤销 (Ctrl+Z)">
        ↶
      </a-button>
      <a-button size="small" :disabled="!canvasStore.canRedo" @click="canvasStore.redo" title="重做 (Ctrl+Y)">
        ↷
      </a-button>

      <a-divider type="vertical" />

      <!-- 对齐工具 -->
      <a-dropdown>
        <a-button size="small">
          📐 对齐
        </a-button>
        <template #overlay>
          <a-menu>
            <a-menu-item @click="canvasStore.alignComponents('left')">
              ⬅️ 左对齐
            </a-menu-item>
            <a-menu-item @click="canvasStore.alignComponents('center')">
              ↔️ 水平居中
            </a-menu-item>
            <a-menu-item @click="canvasStore.alignComponents('right')">
              ➡️ 右对齐
            </a-menu-item>
            <a-menu-divider />
            <a-menu-item @click="canvasStore.alignComponents('top')">
              ⬆️ 上对齐
            </a-menu-item>
            <a-menu-item @click="canvasStore.alignComponents('middle')">
              ↕️ 垂直居中
            </a-menu-item>
            <a-menu-item @click="canvasStore.alignComponents('bottom')">
              ⬇️ 下对齐
            </a-menu-item>
          </a-menu>
        </template>
      </a-dropdown>

      <a-dropdown>
        <a-button size="small">
          📏 分布
        </a-button>
        <template #overlay>
          <a-menu>
            <a-menu-item @click="canvasStore.distributeComponents('horizontal')">
              ↔️ 水平等距
            </a-menu-item>
            <a-menu-item @click="canvasStore.distributeComponents('vertical')">
              ↕️ 垂直等距
            </a-menu-item>
          </a-menu>
        </template>
      </a-dropdown>

      <a-divider type="vertical" />

      <!-- 组合相关操作 -->
      <a-button size="small" :disabled="!canGroup" @click="groupSelectedComponents" title="合并选中组件">
        🔗 合并
      </a-button>
      <a-button size="small" :disabled="!canUngroup" @click="ungroupSelectedComponent" title="打散组合">
        🔓 打散
      </a-button>

      <a-divider type="vertical" />

      <!-- 导入导出 -->
      <a-button size="small" @click="importConfig">
        📁 导入
      </a-button>
      <a-button size="small" @click="exportConfig">
        💾 导出
      </a-button>

      <a-divider type="vertical" />

      <!-- 清空画布 -->
      <a-popconfirm title="确定要清空画布吗？" @confirm="clearCanvas" ok-text="确定" cancel-text="取消">
        <a-button size="small" danger>
          🗑️ 清空
        </a-button>
      </a-popconfirm>

      <!-- 预览 -->
      <a-button size="small" type="primary">
        👁️ 预览
      </a-button>
    </div>

    <!-- 隐藏的文件输入 -->
    <input ref="fileInputRef" type="file" accept=".json" style="display: none" @change="handleFileChange" />
    
    <!-- 重命名页面对话框 -->
    <a-modal 
      v-model:open="showRenameModal" 
      title="重命名页面" 
      @ok="handleRenamePage"
      ok-text="确定"
      cancel-text="取消"
    >
      <a-input 
        v-model:value="newPageName" 
        placeholder="请输入页面名称" 
        @press-enter="handleRenamePage"
      />
    </a-modal>
  </div>
</template>

<style scoped>
.toolbar {
  -webkit-app-region: drag;
}

.toolbar button {
  -webkit-app-region: no-drag;
}
</style>
